/*
 * @Author: your name
 * @Date: 2021-09-01 09:58:19
 * @LastEditTime: 2021-09-06 14:27:29
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \property\sub\faq\src\api\index.js
 */
import axios from "axios";
import router from "../router";
import { Message } from 'element-ui'


axios.defaults.timeout = 20000; //超时时间
axios.defaults.baseURL = process.env.NODE_ENV == 'development' ? '/' : 'http://dev.csstrobot.com:8066/srom'

axios.interceptors.request.use(
  (config) => {
    // console.log('config---------: ', config);
    let { data, params, url } = config;
    let reg = /[\n\r\b\t]/g;
    if (Object.prototype.toString.call(data) == "[object Object]") {
      // console.log('data: ', data);
      for (let index in data) {
        let item = data[index];
        if (Object.prototype.toString.call(item) == "[object String]") {
          data[index] = item.trim();
          data[index] = item.replace(reg, "");
        }
      }
    }
    if (Object.prototype.toString.call(params) == "[object Object]") {
      for (let index in params) {
        let _item = params[index];
        if (Object.prototype.toString.call(_item) == "[object String]") {
          params[index] = _item.trim();
          params[index] = _item.replace(reg, "");
        }
        //   console.log('_item: ', _item);
      }
      // console.log('config.params: ', config.params);
    }
    if (url.indexOf("?") != -1) {
      var theRequest = new Object();
      let baseUrl = url.substring(0, url.indexOf("?") + 1),
        lastUrl = url.substring(url.indexOf("?") + 1, url.length + 1);
      // console.log('lastUrl: ', lastUrl);
      if (lastUrl.length > 0) {
        let strs = lastUrl.split("&");
        // console.log('strs: ', strs);
        for (var i = 0; i < strs.length; i++) {
          let key = strs[i].split("=")[0],
            val = unescape(strs[i].split("=")[1]);
          theRequest[key] =
            Object.prototype.toString.call(val) == "[object String]"
              ? val.replace(reg, "")
              : val;
        }
        for (let item in theRequest) {
          baseUrl += `${item}=${theRequest[item]}&`;
        }
        config.url = baseUrl;
      }
      // console.log('baseUrl: ', baseUrl);
    }
    // console.log('---------------------',Vue.prototype.microStore.getters.token)
    let token = sessionStorage.getItem('access_token') || "";
    if (token) {
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      // config.headers.common['access_token'] = `${token}`;
      if (config.url.indexOf("?") != -1) {
        config.url = config.url + "&access_token=" + token; /*拼接完整请求路径*/
      } else {
        config.url = config.url + "?access_token=" + token;
      }
    }
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

// HTTPresponse拦截
axios.interceptors.response.use(
  (res) => {
    const status = res.status || res.data.status || res.data.code || 200;
    if (status === 401)
      router.push({
        path: "/login",
      });
    return res;
  },
  (error) => {
    // 跳转到登录页面
    // console.log('error code', error.response.orig);
    // console.log('error msg', error.message);
    let status =
      error.status ||
      (error.response &&
        (error.response.status ||
          error.response.data.status ||
          error.response.data.error.status)) ||
      undefined;
    switch (status) {
      case 400:
        error.message = "错误请求";
        error.orig =
          error.orig ||
          error.response.orig ||
          error.response.data.orig ||
          error.response.data.error.orig;
        break;
      case 401:
        error.message = "未获取到用户信息，请重新登录";
        break;
      case 403:
        //  '拒绝访问'
        error.message = "拒绝访问";
        break;
      case 404:
        error.message = `请求地址出错: ${error.response.config.url}`;
        break;
      case 500:
        error.message = "服务器内部错误";
        break;
      case 501:
        error.message = "服务未实现";
        break;
      case 502:
        error.message = "网关错误";
        break;
      case 503:
        error.message = "服务不可用";
        break;
      case 504:
        error.message = "网关超时";
        break;
      default:
        break;
    }
    Message({ type: 'error', message: error.message })
    return Promise.reject(error);
  }
);
export default axios;
